package org.blade.personal.framework.session.concre;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.blade.personal.framework.exception.ColumnRepeatlyException;
import org.blade.personal.framework.orm.EntityAttribute;
import org.blade.personal.framework.orm.TypeAlias;
import org.blade.personal.framework.session.ResultHandler;

/**
 * 结果辅助
 * 
 * @author ZGF
 * @version 0.1
 */
public class ConcreResultHandler implements ResultHandler {

	/**
	 * 合并结果实体属性、结果列别名，最终返回的
	 */
	private Map<String, String> resultObject = new HashMap<String, String>();

	private Map<String, Method> attributeSetter = new HashMap<String, Method>();
	
	private static ResultInfoPicker picker = new ConcreResultInfoPicker();
	
	/**
	 * 结果实体属性:
	 */
	protected Map<String, String> resultEntityAttribute = new HashMap<String, String>();

	/**
	 * 结果列别名；把结果集列的别名与所属实体别名形成映射
	 */
	protected Map<String, String> resultAlise = new HashMap<String, String>();

	/**
	 * 结果映射
	 */
	protected Map<String, String> resultMapping = new HashMap<String, String>();

	@Override
	public void setResultEntityAttribute(TypeAlias alies) {
		// TODO 设置结果集与实体的关系
		EntityAttribute entityAttribute = (EntityAttribute) alies;
		Set<String> attributekeySet = this.resultEntityAttribute.keySet();
		Set<String> alisekeySet = this.resultAlise.keySet();
		if (attributekeySet.contains(entityAttribute.getName())
				|| alisekeySet.contains(alies.getClause())) {
			// TODO 抛出重复列名异常
			throw new ColumnRepeatlyException();
		}
		// TODO 如果需要提升性能，还得在typeAlies里记录Setter方法

		this.resultEntityAttribute.put(entityAttribute.getName(),
				entityAttribute.getOwner());
		this.resultAlise.put(alies.getClause(), entityAttribute.getOwner());
		this.resultObject.putAll(this.resultAlise);
		this.resultObject.putAll(this.resultEntityAttribute);

	}

	public String getEntityName(String columnName) {
		return this.resultObject.get(columnName);
	}
	
	@Override
	public void setSetter(String key, Method setter) {
		this.attributeSetter.put(key, setter);
	}
	
	public ConcreResultHandler() {
		// TODO Auto-generated constructor stub
	}
	
	@Override
	public Method getSetter(String key) {
		return this.attributeSetter.get(key);
	}
	
	 @Override
	public ResultInfoPicker getPicker() {
		 if( picker == null){
			 picker = new ConcreResultInfoPicker();
		 }
		return picker;
	}

}
